import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../viewmodels/task_view_model.dart';

/// 今日打卡tab页
/// 显示当前进行中的打卡任务，并提供打卡功能
class TodayTab extends StatefulWidget {
  const TodayTab({super.key});

  @override
  State<TodayTab> createState() => _TodayTabState();
}

class _TodayTabState extends State<TodayTab> {
  final Set<String> _selectedTaskIds = {};

  @override
  void initState() {
    super.initState();
    // 初始化时加载任务
    Provider.of<TaskViewModel>(context, listen: false).loadOngoingTasks();
  }

  void _toggleTaskSelection(String taskId) {
    setState(() {
      if (_selectedTaskIds.contains(taskId)) {
        _selectedTaskIds.remove(taskId);
      } else {
        _selectedTaskIds.add(taskId);
      }
    });
  }

  void _markSelectedAsCompleted() {
    final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
    final today = DateTime.now();
    for (final taskId in _selectedTaskIds) {
      taskViewModel.toggleTaskCompletion(taskId, today);
    }
    setState(() {
      _selectedTaskIds.clear();
    });
  }

  void _markAllAsCompleted() {
    final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
    taskViewModel.markAllTodayAsCompleted();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<TaskViewModel>(
        builder: (context, taskViewModel, child) {
          if (taskViewModel.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          if (taskViewModel.ongoingTasks.isEmpty) {
            return const Center(
              child: Text('今天没有打卡任务'),
            );
          }

          return Column(
            children: [
              Expanded(
                child: ListView.builder(
                  itemCount: taskViewModel.ongoingTasks.length,
                  itemBuilder: (context, index) {
                    final task = taskViewModel.ongoingTasks[index];
                    return CheckboxListTile(
                      value: _selectedTaskIds.contains(task.id),
                      onChanged: (value) {
                        _toggleTaskSelection(task.id);
                      },
                      title: Text(task.name),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('进度: ${task.progress}'),
                          Text('${task.startDate.toString().split(' ')[0]} - ${task.endDate.toString().split(' ')[0]}'),
                        ],
                      ),
                      secondary: Icon(
                        task.isTodayCompleted(DateTime.now())
                            ? Icons.check_circle
                            : Icons.circle_outlined,
                        color: task.isTodayCompleted(DateTime.now()) ? Colors.green : null,
                      ),
                    );
                  },
                ),
              ),
              if (_selectedTaskIds.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ElevatedButton(
                    onPressed: _markSelectedAsCompleted,
                    child: const Text('打卡所选任务'),
                  ),
                ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: _markAllAsCompleted,
                  child: const Text('一键打卡'),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}